// pages/createIssue/createIssue.js
const app = getApp();
const path = app.globalData.path;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    path: [],
    imgs: [],
    upload_picture_list: [],
    programList: null,
    vehicleList: null,
    productTypeList: null,
    processStatus: 'DRAFT',
    list: '',
    title: '',
    sourceId: '',
    reportOrg: '',
    reportBy: ''
  },

  // logout(e){
  //   wx.removeStorageSync('token');
  //   wx.clearStorageSync();
  //   wx.navigateTo({
  //     url: '../../login/login',
  //   })
  // },

  getIssueTitle: function(result, loginFlag, that) {
    // 根据问题信息已返回的结果 
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueSourceList.action',
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      success: function(response) {

        var sourceList = JSON.parse(response.data);
        var sourceArray = sourceList.data;
        var issueSourceId = result.data.issueSourceId; // 获取问题信息返回结果中的 issueSourceId

        for (var i = 0; i < sourceArray.length; i++) {
          if (issueSourceId == sourceArray[i].id) {
            that.setData({
              issueSourceTitle: sourceArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  getIssueTypeTitle: function(result, loginFlag, that) {
    var that = this;
    // var path = getApp().path;
    wx.request({
      url: path + 'wx-issue/q-iissue!getIssueTypeList.action',
      //发送的数据
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      //成功回调
      success: function(res) {

        var issueType = JSON.parse(res.data);
        var issueTypeArray = issueType.data;
        var issueTypeId = result.data.issueTypeId;

        for (var i = 0; i < issueTypeArray.length; i++) {
          if (issueTypeId == issueTypeArray[i].id) {
            that.setData({
              issueTypeTitle: issueTypeArray[i].title
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  getPartTypeName: function(result, loginFlag, that) {

    // 根据问题信息已返回的结果productTypes作为参数 再发送一个request .
    wx.request({
      url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',

      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        productTypes: result.data.productTypes
      },
      success: function(r) {
        // console.log(r.data);
        var pmPartTypes = JSON.parse(r.data);

        // 从返回的数据中找到 问题信息 中对应的零件类别  
        // that.setData({
        //   productTypeList: pmPartTypes.data
        // })

        var partArray = pmPartTypes.data;
        var issuePartTypeId = result.data.partTypeId; // 获取问题返回结果中的 partTypeId

        for (var i = 0; i < partArray.length; i++) {
          if (issuePartTypeId == partArray[i].id) {
            that.setData({
              partTypeName: partArray[i].name
            })
            return;
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  // 删除按钮先reset  然后删除问题
  formreset: function(e) {
    var that = this;
    console.log(e);

    that.setData({
      src: '',
      path: [],
      imgs: [],
      upload_picture_list: [],
      sourceId: null,
      idx: null,
      issueInfo: {
        subPart: null,
        issueDescription: ''
      },
      issueLevelIndex: null,
      issueTypeIndex: null,
      processStatus: 'DRAFT',
      programIndex: null,
      productTypeIndex: null,
      reportBy: null,
      reportByName: null,
      reportOrg: null,
      sourceId: null,
      vehicleIndex: null
    });
    console.log('data',that.data);
  },

  formsubmit: function(e) {

  },

  issueSave: function() {

  },

  issueSubmit: function() {

  },

  issueDelete: function() {

  },

  backToIssueList: function() {
    wx.switchTab({
      url: '../issueList/issueList',
      success: function(e) {
        var page = getCurrentPages().pop();
      }
    });
  },

  //选择图片方法之前 先提交表单的数据
  uploadpic: function (e) {
    let that = this;
    let loginFlag = wx.getStorageSync('token');
    console.log(e);

    if (e.detail.value.title == "") {
      wx.showToast({
        title: '请先输入标题',
        icon: 'none'
      })
      return;
    }

    //TODO 分开地下 function form 应该跑的流程为: formsubmit（按钮判断）> 提交(issueSubmit) 或 保存(issueSave) 或 删除(issueDelete)

    // 点击添加图片的加号  就提交表单 创建Issue 返回issueId
    var btn = e.detail.target.dataset.btn;

    if (btn == "save") { // 用户点击了保存按钮

      if (that.data.sourceId != "") { // 点过添加图片的加号 也就是已经保存过 直接跳转到问题列表

        that.formreset();
        that.backToIssueList();

      } else { // 没点过也就是没保存过

        that.createIssue(e, "", 'DRAFT');

      }

      return;

    } else if (btn == "submit") { // 点击提交按钮

      // 判断用户有没有上传图片的操作 如果上传了图片那么sourceId 有值。
      wx.showLoading();
      if (that.data.sourceId != "") { // 曾保存为草稿 
        that.createIssue(e, that.data.sourceId, 'ASIGN'); //更新这个issue 发起流程 进入“分配”节点  
      } else {
        that.createIssue(e, "", 'ASIGN'); // 创建issue 发起流程 进入“分配”节点
      }
      wx.hideLoading();
      that.formreset();
      that.backToIssueList();
      return;

    } else if (btn == "delete") { //新建问题删除

      if (loginFlag) {

        wx.showLoading();
        wx.request({
          url: path + '/wx-issue/q-iissue!removeIssue.action',
          header: {
            'token': loginFlag
          },
          data: {
            issueId: that.data.sourceId
          },
          dataType: "JSON",
          success: function (res) {

            var result = JSON.parse(res.data);

            that.formreset();
            wx.hideLoading();
            wx.showToast({
              title: '问题已删除',
              duration: 1500
            });
            wx.switchTab({
              url: '../issueList/issueList'
            });
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }

    } else if (btn == "upload") {

      if (that.data.sourceId == "") { //
        //     console.log("创建了问题");
        that.createIssue(e, "", 'DRAFT'); // 创建草稿
      }
      //   console.log(that.data.sourceId);
      let pic_list = that.data.upload_picture_list;
      let imgs = that.data.imgs;

      var uploadUrl = path + 'wx-com/image!uploadCmImage.action';
      wx.chooseImage({
        count: 8, // 默认9，这里显示一次选择相册的图片数量 
        sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有  
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
          // console.log(res);
          var tempFiles = res.tempFiles
          //把选择的图片 添加到集合里
          for (let i in tempFiles) {
            tempFiles[i]['upload_percent'] = 0
            tempFiles[i]['path_server'] = ''

            imgs.push(tempFiles[i].path);
            //  console.log(imgs);
            //upload_file_server(uploadUrl,that,tempFiles,that.data.sourceId,i,loginFlag)

            wx.showLoading({ title: '正在上传....' });
            wx.uploadFile({
              // 模拟https
              url: uploadUrl, //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
              filePath: tempFiles[i].path, //上传的文件本地地址    
              name: 'upload',
              header: {
                'token': loginFlag
              },
              formData: {
                'num': i,
                'source': 'QIM_ISSUE_IMAGE',
                'sourceId': that.data.sourceId
              },
              //附近数据，这里为路径     
              success: function (res) {
                //   console.log(res);
                var result = JSON.parse(res.data);
                //   console.log(result);
                tempFiles[i].imageId = result.data.id;
                // //字符串转化为JSON  
                console.log("--------------");
                //   console.log(tempFiles);

                pic_list.push(tempFiles[i])
                // if (data.Success == true) {
                //   var filename = data.file //存储地址 显示
                //   tempFiles[i]['path_server'] = filename
                // } else {
                //   tempFiles[i]['path_server'] = filename
                // }
                that.setData({
                  upload_picture_list: pic_list
                });

                wx.hideLoading();

                //wx.setStorageSync('imgs', upload_picture_list);
              }
            })
          }

          console.log(that.data.upload_picture_list);
          //显示
          // that.setData({
          //   upload_picture_list: pic_list,
          //   imgs: imgs
          // });
        }
      })
    }

  },

  // 点击删除图片
  deleteImg(e) {
    let picList = this.data.upload_picture_list;
    let index = e.currentTarget.dataset.index;


    console.log(index);
    wx.showToast({
      title: '删除中...',
    })
    var loginFlag = wx.getStorageSync('token');


    // 用索引获取list中图片对象  从对象中取出 上传图片时存入的imageId 然后用imageId 从数据库中删除图片。
    wx.request({
      url: path + "wx-com/image!deleteCmImage.action",
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        id: picList[index].imageId
      },
      success: function(res) {
        // console.log(res.data);
        // var result = JSON.parse(res.data);
        // that.setData({
        //   sourceId: result.data.issueId
        // })
        // console.log(that.data.sourceId);
        wx.hideToast();

      },
      fail: function(res) {
        console.log(res);
      }
    })
    picList.splice(index, 1);

    this.setData({
      upload_picture_list: picList
    });
  },



  // 预览图片
  previewImg(e) {
    console.log(e);
    //获取当前图片的下标
    let index = e.currentTarget.dataset.index;

    console.log(index);
    //所有图片
    let imgs = this.data.imgs;

    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },


  selectRole(e) {
    wx.navigateTo({
      url: '../createIssue/createRole',
    })
  },

  createIssue(e, issueId, lifecycleStatus) {
    var that = this;
    var url = path + "wx-issue/q-iissue!createQIIssue.action";
    let loginFlag = wx.getStorageSync('token');
    var model = {};
    let o = e.detail.value;
    model.title = o.title;

    model.issueSourceId = that.data.issueSourceList[o.issueSourceId].id;

    model.programId = that.data.programList[o.programId].id;

    model.programVehicleId = that.data.vehicleList[o.programVehicleId].id;

    model.partTypeId = that.data.productTypeList[o.partTypeId].id;

    model.reportOrg = that.data.reportOrg;

    model.reportBy = that.data.reportBy;

    model.reportByName = o.reportByName;

    model.reportDate = o.reportDate;

    model.subPart = o.subPart;

    model.issueLevel = that.data.issueLevelList[o.issueLevel].code;

    model.issueTypeId = that.data.issueTypeList[o.issueTypeId].id;

    model.issueDescription = o.issueDescription;

    model.lifecycleStatus = lifecycleStatus; // 标识为草稿 不发起流程
    console.log(e);
    console.log(model);
    wx.request({
      url: url,
      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        model: model,
        issueId: issueId
      },
      success: function(res) {
        console.log(res.data);
        var result = JSON.parse(res.data);
        that.setData({
          sourceId: result.data.issueId
        })
        console.log(that.data.sourceId);

      },
      error: function(res) {
        console.log(res);
      }
    })



  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var date = that.getNowFormatDate();

    that.setData({
      date: date
    })
    console.log(date);
    var screenHeight = wx.getSystemInfoSync().windowHeight;
    const query = wx.createSelectorQuery();
    var album = query.select('album');
    var issueInfo = wx.getStorageSync('issueInfo');
    var programList = null;
    var issueSourceList = null;
    var issueTypeList = null;

    // console.log(album);
    // const query = wx.createSelectorQuery();
    // query.select('.album')
    // this.ctx = wx.createCameraContext()
    // console.log(screenHeight);

    let loginFlag = wx.getStorageSync('token');
    if (loginFlag) {
      // 查询问题来源列表
      wx.request({
        url: path + 'wx-issue/q-iissue!getIssueSourceList.action',
        header: {
          'token': loginFlag
        },
        dataType: "JSON",
        success: function(res) {

          var result = JSON.parse(res.data);

          that.setData({
            issueSourceList: result.data
          });
          var issueSourceList = result.data;
          // console.log(that.data.issueSourceList);
        },
        fail: function(res) {
          console.log(res);
        }
      })

      // 查询项目列表
      wx.request({
        url: path + 'wx-pm/project-open-issue!getProgramList4RaiseIssue.action',

        header: {
          'token': loginFlag
        },
        dataType: "JSON",
        success: function(res) {
          console.log(res.data);
          var result = JSON.parse(res.data);
          console.log(result);
          that.setData({
            programList: result.data
          });
          var programList = result.data;
        },
        fail: function(res) {
          console.log(res);
        }
      })

      // 查询问题等级列表
      wx.request({
        url: path + 'wx-issue/q-iissue!getIssueLevelList.action',
        header: {
          'token': loginFlag
        },
        dataType: "JSON",
        success: function(res) {

          var result = JSON.parse(res.data);
          console.log(result.data);
          that.setData({
            issueLevelList: result.data
          });
          var issueLevelList = result.data;
        },
        fail: function(res) {
          console.log(res);
        }
      })

      wx.request({
        url: path + 'wx-issue/q-iissue!getIssueTypeList.action',

        header: {
          'token': loginFlag
        },
        dataType: "JSON",
        //成功回调
        success: function(res) {

          var result = JSON.parse(res.data);

          that.setData({
            issueTypeList: result.data
          });
          var issueTypeList = result.data;
        },
        fail: function(res) {
          console.log(res);
        }
      });

    } else {
      // 无skey，作为首次登录
      wx.navigateTo({
        url: '../../login/login',
      })
    }

  },


  // 问题来源点击事件
  issueSourceChange: function(e) {
    this.setData({ //给变量赋值
      idx: e.detail.value
    })
  },
  // 车型点击事件
  vehicleChange: function(e) {
    this.setData({ //给变量赋值
      vehicleIndex: e.detail.value
    })
  },
  // 提出时间

  dateChange: function(e) {
    this.setData({
      date: e.detail.value
    })

  },

  issueLevelListChange: function(e) {
    this.setData({
      issueLevelIndex: e.detail.value,
    })
  },
  // 问题类型Change事件
  issueTypeListChange: function(e) {
    this.setData({
      issueTypeIndex: e.detail.value,
    })
  },

  productTypeListChange: function(e) {

    this.setData({
      productTypeIndex: e.detail.value,
    })
  },
  //获取当前时间，格式YYYY-MM-DD
  getNowFormatDate: function() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  },

  // 项目点击事件
  programChange: function(e) {
    var that = this;

    that.setData({
      programIndex: e.detail.value,
    })

    let loginFlag = wx.getStorageSync('token');
    var programId = this.data.programList[this.data.programIndex].id;
    var productTypes = this.data.programList[this.data.programIndex].productTypes;
    console.log(productTypes);
    // 根据项目查询车型
    wx.request({
      url: path + 'wx-pm/project-open-issue!getVehicleList4RaiseIssue.action',
      header: {
        'token': loginFlag,
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      dataType: "JSON",
      data: {
        programId: programId
      },
      success: function(res) {

        var result = JSON.parse(res.data);

        that.setData({
          vehicleList: result.data
        })
      },
      error: function(res) {
        console.log(res);
      }
    })

    // 根据项目中产品类别programTypes的值查询零件类别
    wx.request({
      url: path + 'wx-issue/q-iissue!getPmPartTypeList.action',

      header: {
        'token': loginFlag
      },
      dataType: "JSON",
      data: {
        productTypes: productTypes
      },
      success: function(res) {
        console.log(res.data);
        var result = JSON.parse(res.data);
        that.setData({
          productTypeList: result.data
        })
      },
      fail: function(res) {
        console.log(res);
      }
    })


  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})


/**
 * 上传图片方法
 */
function upload_file_server(url, that, tempFiles, i, sourceId, token) {
  //上传返回值
  console.log(tempFiles);
  const upload_task = wx.uploadFile({
    // 模拟https
    url: url, //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
    filePath: tempFiles[i].path, //上传的文件本地地址    
    name: 'upload',
    header: {
      'token': token
    },
    formData: {
      'num': i,
      'source': 'QIM_ISSUE_IMAGE',
      'sourceId': sourceId
    },
    //附近数据，这里为路径     
    success: function(res) {
      var data = JSON.parse(res.data);
      // //字符串转化为JSON  
      console.log("--------------");
      console.log(tempFiles);
      if (data.Success == true) {
        var filename = data.file //存储地址 显示
        tempFiles[i]['path_server'] = filename
      } else {
        tempFiles[i]['path_server'] = filename
      }
      that.setData({
        //  upload_picture_list: upload_picture_list
      });
      //wx.setStorageSync('imgs', upload_picture_list);
    }
  })
  //上传 进度方法
  upload_task.onProgressUpdate((res) => {
    console.log(res);
    console.log(res.progress);

    tempFiles[i]['upload_percent'] = res.progress
    that.setData({
      //  upload_picture_list: upload_picture_list
    });
  });

}